package com.shimao.celnet.payment.controller.api;


import com.shimao.celnet.payment.model.PPayCUPUser;
import com.shimao.celnet.payment.model.PPayCust;
import com.shimao.celnet.payment.model.request.CallIn_outCUPApplicationReqIn;
import com.shimao.celnet.payment.model.response.ErrorInfoEnum;
import com.shimao.celnet.payment.model.response.ResponseJson;
import com.shimao.celnet.payment.service.*;
import com.shimao.celnet.payment.service.impl.apiservice.CallOut_TLPublicService;
import com.shimao.celnet.payment.util.FinalUtil;
import io.swagger.annotations.Api;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

/**
 * 银联绑卡签约申请接口
 * 外部系统 → 支付系统，数据：绑卡签约申请数据
 * Created by galen on 2018/11/20.
 */
@RestController
@RequestMapping(value = "/payment")
@Api("接口：pay-201(银联)-外部银联绑卡签约申请<outSignedApplicationReIn> 外部系统 → 支付系统，数据：绑卡签约申请数据")
public class CallIn_outSignedApplicationReInContrller {
    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private PPayCupUserService pPayCupUserService;

    @Autowired
    private BEstateService estateService;

    @Autowired
    private BHouseService houseService;

    @Autowired
    private PPayBusinessService businessService;

    @Autowired
    private PPayCustService pPayCustService;

    @Autowired
    private CallOut_TLPublicService callOut_tlPublicService;


    @RequestMapping(value = "/agreeApplyReq",method = RequestMethod.POST)
    public String outSignApplicationReqInf(@RequestBody @Valid CallIn_outCUPApplicationReqIn requestJson, BindingResult result) {
        ResponseJson retJson = new ResponseJson(ErrorInfoEnum.SUCCESS, "");
        logger.info("pay-201-外部银联绑卡签约申请<outSignedApplicationReIn>请求JSON:" + requestJson.toString());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //通过valid验证
        if (result.hasErrors()) {
            for (FieldError error : result.getFieldErrors()) {
                logger.debug("缺少必要参数：" + error.getDefaultMessage());
                retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS, error.getDefaultMessage());
                return retJson.toString();
            }
        }
        String appKey = request.getHeader(FinalUtil.HEADER_APP_KEY);//获取header中的app_key
        String interfaceId = request.getHeader(FinalUtil.HEADER_INTERFACE_ID);//获取header中的interface_id
        logger.info("应用编号：" + appKey);
        logger.info("接口编号：" + interfaceId);
        //获取绑卡信息
        PPayCUPUser payCUPUser = new PPayCUPUser();
        payCUPUser.setPayMeruserid(requestJson.getMeruserid());
        payCUPUser.setPayAcctname(requestJson.getAcctname());
        payCUPUser.setPayMobile(requestJson.getMobile());
        payCUPUser.setPayIdno(requestJson.getIdno());
        payCUPUser.setPayAccttype(requestJson.getAccttype());
        payCUPUser.setPayAcctno(requestJson.getAcctno());
        payCUPUser.setPayCvv2(requestJson.getCvv2());
        payCUPUser.setPayValiddate(requestJson.getValiddate());
        payCUPUser.setAppKey(appKey);
        payCUPUser.setInterfaceId(interfaceId);
        //商户id
        String estateGuid = estateService.getBySfGuid(requestJson.getCustSfGuid()).getGuid();//小区
        if (estateGuid != null && !"".equals(estateGuid)) {
            payCUPUser.setPayCustid(estateGuid);
        } else {
            String businessGuid = businessService.getByGuid(requestJson.getCustSfGuid()).getCompanySfguid();  //商户id
            if (businessGuid != null && !"".equals(businessGuid)) {
                payCUPUser.setPayCustid(businessGuid);
            } else {
                String houseGuid = houseService.getBySfGuid(requestJson.getCustSfGuid()).getEstateGuid();//房间id
                payCUPUser.setPayCustid(houseGuid);
                if (houseGuid == null) {
                    retJson = new ResponseJson(ErrorInfoEnum.ERROR_PARAMS, "商户号<custSfGuid>");
                    return retJson.toString();
                }
            }
        }
        //商户信息
        PPayCust payCust = getTLMessage(payCUPUser.getPayCustid(), FinalUtil.CUP_PAY_TYPE);
        try {//请求通联签约申请接口
            logger.info("==================请求通联申请签约开始=====================");
            logger.info("========绑卡用户号：" + payCUPUser.getPayMeruserid() + "=========商户号：" + payCust.getCustId());
            Map<String, String> map = callOut_tlPublicService.agreeapply(payCUPUser, payCust);
            logger.info("========通联响应参数：" + map.toString());
            if ("SUCCESS".equals(map.get(FinalUtil.RETCDE))){
                retJson.setErrorMessage(map.get(FinalUtil.ERRMSG));
                retJson.addBody(FinalUtil.TRXSTATUS,map.get(FinalUtil.TRXSTATUS));
                retJson.addBody(FinalUtil.THPINFO,map.get(FinalUtil.THPINFO));
                payCUPUser.setPayThpinfo(map.get(FinalUtil.THPINFO));
                //保存绑卡信息
                pPayCupUserService.save(payCUPUser);
            }else {
                retJson = new ResponseJson(ErrorInfoEnum.PAY_RESULT_TYPE, "FAIL");
                return retJson.toString();
            }
        } catch (Exception e) {
            logger.debug("通联异常参数：" + e.getMessage());
            e.printStackTrace();
            retJson = new ResponseJson(ErrorInfoEnum.PAY_RESULT_TYPE, e.getMessage());
        }
        //创建json
        return retJson.toString();
    }

    /**
     * 根据小区sfid查询通联账户信息
     *
     * @param estateGuid
     * @return
     */
    public PPayCust getTLMessage(String estateGuid, String payType) {
        return pPayCustService.getBySfGuid1(estateGuid, payType);
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public JSONObject sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            //connection.setRequestProperty("accept", "*/*");
            //connection.setRequestProperty("connection", "Keep-Alive");
            // connection.setRequestProperty("user-agent",
            //         "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
           /* for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }*/
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return JSONObject.fromObject(result) ;
    }

}
